package com.aube.base.card;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.aube.base.model.OptionResultModel;
import com.aube.base.model.ReportResultModel;
import com.aube.base.model.TimeLinePiece;
import com.aube.interact.base.R;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.utils.Utils;


/**
 * Created by hill on 16/11/1.
 */

public class InfoView extends BaseCardNew {
    private final String TAG = "Aube/InfoView";
    private Context mContext;

    private ImageView mBgImg;
    private WebView mWebView;

    public InfoView(Context context) {
        this(context, null);
    }
    public InfoView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public InfoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
    }

    @Override
    public void init(final TimeLinePiece data, ChannelDetail detail) {
        super.init(data, detail);
        initView();
    }

    @Override
    protected void initView() {
        LayoutInflater.from(getContext()).inflate(R.layout.aube_intera_layout_sdk_info, this);

        mBgImg = (ImageView) findViewById(R.id.sdk_info_bgimg);
        mRoot = (FrameLayout) findViewById(R.id.sdk_info_root);
        mFoldText = (TextView) findViewById(R.id.sdk_info_expand);
        mCloseView = findViewById(R.id.sdk_info_close);
        mWebView = (WebView) findViewById(R.id.sdk_info_webview);
        mBetterCloseView = findViewById(R.id.sdk_info_closeclickview);

        if(mData.detail.pic != null)
            ImageLoader.getInstance(getContext()).fillImage(mBgImg, mData.detail.pic.picurl);

        setupWebView();

        super.initView();

        Utils.Log(Utils.LogType.DEBUG, TAG, "init end");
    }

    @Override
    protected void setupFoldLayout() {
        boolean bFold = mData.isCardFold();
        if(bFold) {
            mBExpanded = false;
            mFoldText.setText("点击展开");
            mFoldText.setCompoundDrawables(null, null, null, null);
            mWebView.setVisibility(View.GONE);
            mBgImg.setVisibility(View.VISIBLE);
            LayoutParams params = new LayoutParams(Utils.dip2px(mContext, 180), Utils.dip2px(mContext, 100));
            mRoot.setLayoutParams(params);
            mRoot.requestLayout();
        } else {
            mBExpanded = true;
            mFoldText.setText("收起  ");
            mFoldText.setCompoundDrawables(null, null, mFoldDrawable, null);
            mWebView.setVisibility(VISIBLE);
            mBgImg.setVisibility(GONE);
            LayoutParams params = new LayoutParams(Utils.dip2px(mContext, 180), ViewGroup.LayoutParams.MATCH_PARENT);
            mRoot.setLayoutParams(params);
            mRoot.requestLayout();
        }
    }

    @Override
    protected void switchFoldLayout() {
        if(mBExpanded) {
            mBExpanded = false;
            mFoldText.setText("点击展开");
            mFoldText.setCompoundDrawables(null, null, null, null);
            mWebView.setVisibility(View.GONE);
            mBgImg.setVisibility(View.VISIBLE);
            LayoutParams params = new LayoutParams(Utils.dip2px(mContext, 180), Utils.dip2px(mContext, 100));
            mRoot.setLayoutParams(params);
            mRoot.requestLayout();

            startCollapseAnim();
        } else {
            mBExpanded = true;
            mFoldText.setText("收起  ");
            mFoldText.setCompoundDrawables(null, null, mFoldDrawable, null);
            mWebView.setVisibility(VISIBLE);
            mBgImg.setVisibility(GONE);
            LayoutParams params = new LayoutParams(Utils.dip2px(mContext, 180), ViewGroup.LayoutParams.MATCH_PARENT);
            mRoot.setLayoutParams(params);
            mRoot.requestLayout();

            startExpandAnim();
        }
    }

    private boolean bWebviewLoading = true;
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // Fix that when defaul is not fold, webview loading is too slow to appear which leads to mismatch height at first time
        if(mWebView.getVisibility() == VISIBLE && bWebviewLoading) {
            measureChild(getChildAt(0), MeasureSpec.makeMeasureSpec(widthMeasureSpec, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(((View)getParent()).getMeasuredHeight(), MeasureSpec.EXACTLY));
            setMeasuredDimension(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(((View)getParent()).getMeasuredHeight(), MeasureSpec.EXACTLY));
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        bWebviewLoading = false;
    }

    private int oriBGWidth = 0;

    @Override
    protected void startExpandAnim() {
        Utils.Log(Utils.LogType.DEBUG, TAG, "startExpandAnim begin");
        clearAnimation();

        final int finalHeight = ((View)getParent()).getHeight();
        final int oriHeight = mRoot.getHeight();
        oriBGWidth = mBgImg.getWidth();

        ValueAnimator animator = ValueAnimator.ofFloat(0.0f, 1.0f);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation){
                float animValue = (float) animation.getAnimatedValue();

                LayoutParams params = (LayoutParams) mRoot.getLayoutParams();
                params.height = (int) (oriHeight + (finalHeight - oriHeight) * animValue);

                mRoot.setLayoutParams(params);

//                mBgImg.setScaleX(1 - animValue);
//                mBgImg.setScaleY(1 - animValue);
//                mBgImg.setPivotX(0.5f * oriBGWidth);
//                mBgImg.setPivotY(1.0f * params.height);

                mBgImg.setAlpha(1 - animValue);
            }
        });

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mBgImg.setVisibility(View.GONE);
                mBExpanded = true;
            }
        });

        animator.setDuration(800);
        animator.setInterpolator(new DecelerateInterpolator());

        // set target
        animator.setTarget(mRoot);
        animator.start();

        Utils.Log(Utils.LogType.DEBUG, TAG, "startExpandAnim done");
    }

    @Override
    protected void startCollapseAnim() {
        Utils.Log(Utils.LogType.DEBUG, TAG, "startCollapseAnim begin");
        clearAnimation();

        final int finalHeight = ((View)getParent()).getHeight();
        final int targetHeight = Utils.dip2px(mContext, 100);

        ValueAnimator animator = ValueAnimator.ofFloat(0.0f, 1.0f);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation){
                float animValue = (float) animation.getAnimatedValue();

                LayoutParams params = (LayoutParams) mRoot.getLayoutParams();
                params.height = (int) (finalHeight - (finalHeight - targetHeight) * animValue);

                mRoot.setLayoutParams(params);

//                mBgImg.setScaleX(animValue);
//                mBgImg.setScaleY(animValue);
//                mBgImg.setPivotX(0.5f * oriBGWidth);
//                mBgImg.setPivotY(1.0f * params.height);

                mBgImg.setAlpha(animValue);
            }
        });

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mBExpanded = false;
            }
        });

        animator.setDuration(800);
        animator.setInterpolator(new DecelerateInterpolator());

        // set target
        animator.setTarget(mRoot);
        animator.start();

        Utils.Log(Utils.LogType.DEBUG, TAG, "startCollapseAnim done");
    }

    private void show() {
        this.setVisibility(View.VISIBLE);
    }

    @Override
    public String getType() {
        return TYPE_INFO;
    }

    @Override
    public void doNext() {
    }

    @Override
    public void syncData(OptionResultModel response) {
    }

    private boolean mBPreviewDataSynced = false;

    @Override
    public boolean IsPreviewDataSynced() {
        return mBPreviewDataSynced;
    }

    @Override
    public void syncPreviewData(ReportResultModel result) {
    }

    private void setupWebView() {
        String content = mData.detail.content;
        String prefix = "<html>\n" +
                "<meta name=\"viewport\" content=\"minimum-scale=1, maximum-scale=1,  initial-scale=1, user-scalable=yes, width=device-width\" />\n" +
                "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n" +
                "<style>\n" +
                "img{\n" +
                "max-width: 100% !important;\n" +
                "height: auto !important;\n" +
                "}\n" +
                "* {\n" +
                "word-wrap: break-word;\n" +
                "word-break: break-all;\n" +
                "}\n" +
                "body {line-height:130%}" +
                "</style>\n" +
                "<body>\n" +
                "<font color=#F5F5F5 size=2>\n";
        String suffix = "\n</font>\n" +
                "</body>\n" +
                "</html>\n";

        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.setBackgroundColor(mContext.getResources().getColor(R.color.transparent));
        mWebView.loadData(prefix + content + suffix, "text/html; charset=UTF-8", null);
    }

}